<?php

namespace app\merchant\controller;

use app\common\controller\CarddateTests;
use app\common\controller\CardRack;
use app\common\controller\Helpinfo;
use app\common\controller\Platurl;
use app\common\controller\TemplateMsg;

use app\common\controller\AdminBase;
use app\common\controller\TestBase;
use app\common\model\CardGift;
use app\common\model\CardGiftConsume;
use app\common\model\CardGiftPayOrder;
use app\common\model\CardGiftRack;
use app\common\model\CardUrlDict;
use app\common\model\CardUserGetGift;
use app\common\model\Momerchant;

use app\common\model\CardBonusRule;
use app\common\model\CardCzLog;
use app\common\model\CardGivecardLog;
use app\common\model\CardMember;
use app\common\model\CardPaycardlog;
use app\common\model\CardQrcode;
use app\common\model\CardUserGet;
use app\common\model\CardRank;
use app\common\model\Agent;
use app\common\model\CardUserGetAli;
use app\common\model\CardUserUpdate;
use app\common\model\CardCzgive;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;

use think\Config;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardgiftstest extends TestBase
{
    //礼品卡列表
    public function cardgiftlist()
    {
        //搜索条件
        $request = request();
        $arrp = $request->get();
        unset($arrp['page']);
        $map = [];
        if ($arrp) {
            $map['title'] = ['like', '%' . trim($arrp['key']) . '%'];
        } else {
            $arrp['title'] = '';
        }
        $CardGift = new CardGift();
        $mid = $this->get_mer_mid();
        if ($mid !== '') {
            $map['mid'] = ['in', $mid];
        } else {
            $map['top_mid'] = Session::get('login_top_mid');
        }
        $list = $CardGift->where($map)->paginate(10, false, ['key' => request()->param()]);
        $mab['card_type'] = 'GENERAL_CARD';
        $mab['top_mid'] = Session::get('login_top_mid');
        $only = $CardGift->where($mab)->find();
        if ($only) {
            $card['only'] = 1;
        } else {
            $card['only'] = 0;
        }
        $this->assign('card', $card);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //获取礼品卡列表
    public function getcardgiftlist(){
        $CardGift = new CardGift();
        $mid = $this->get_mer_mid();
        if ($mid !== '') {
            $map['mid'] = ['in', $mid];
        } else {
            $map['top_mid'] = Session::get('login_top_mid');
        }
        $list = $CardGift->where($map)->field('card_id,title')->select();
        if ($list){
            $rarr['code'] = 0;
            $rarr['message'] = 'success';
            $rarr['data'] = $list;
        }else{
            $rarr['code'] = 9001;
            $rarr['message'] = 'error';
            $rarr['data'] = $list;
        }
        return json($rarr);
    }


    //创建卡券
    public function creatcardgift()
    {
        $CardGift = new CardGift();
        if (Request()->isPost()) {
            $carddate = new CarddateTests();
            $arr = request()->post();
            $data = $carddate->addcardgift($arr, 1);
//            return json($data);
            //初始化微信API
            $options = $this->option($arr['mid']);
            $wxObj = new Wxobjopen($options);
            //向接口发送创建
            $res = $wxObj->createUserCard($data);
            //错误提示翻译
            $Helpinfo = new Helpinfo();
            $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
            //END
            if ($res['errcode'] == 0) {
                //获取存储数据
                $datas = $carddate->addcardgift($arr, 2, $data, $res);
                $conten = $CardGift->allowField(true)->save($datas);
                if ($conten !== false) {
                    $this->redirect('cardgifts/cardgiftlist');
                } else {
                    $this->error('创建失败', 'cardgifts/cardgiftlist', '', 30);
                }
            } else {
                $this->error('创建失败' . $res['errcode'] . ':' . $errmsg, 'cardgifts/cardgiftlist', '', 30);
            }
        } else {
            $auth_type = $this->get_auth_type();
            if ($auth_type) {
                $card = [];
                $CardUrlDict = new CardUrlDict();
                $Momerchant = new Momerchant();
                $Platurl = new Platurl();
                $url['platurl'] = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
                $urllist = $CardUrlDict->where('type', 1)->select();
                $urllists = $CardUrlDict->where('type', 2)->select();
                $moinfo = $Momerchant->where(['id' => Session::get('login_top_mid')])->field('img_wx,merchant_name,tel,cust_call')->find();
                $this->assign('moinfo', $moinfo);
                $this->assign('urllists', $urllists);
                $this->assign('urllist', $urllist);
                $this->assign('card', $card);
                $this->assign('url', $url);
                //门店
                $Merchant = new Merchant();
                $map['id'] = ['in', $this->get_mer_mid()];
                $map['wx_open_id'] = ['neq',''];
                $mach = $Merchant->where($map)->field('id,sub_mch_id,merchant')->select();
                $this->assign('mach', $mach);
                return $this->fetch();
            } else {
                $this->success('请前往设置微信授权。', 'index/index');
            }

        }

    }


    //修改卡券
    public function editcardgift()
    {
        $card_id = request()->param('card_id');
        if ($card_id) {
            $CardGift = new CardGift();
            $mapm['card_id'] = $card_id;
            $mapm['top_mid'] = Session::get('login_top_mid');
            $info = $CardGift->where($mapm)->find()->toArray();;
            if ($info) {
                if (Request()->isPost()) {
//                    $carddate = new CarddateTests();
//                    $arr = request()->post();
//                    return json($arr);
//                    $arr['card_id'] = $card_id;
//                    $data = '';
//                    //初始化微信API
//                    $options = $this->options($card_id);
//                    $wxObj = new Wxobjopen($options);
//                    //向接口发送修改
//                    $res = $wxObj->updateUserCard($data);
//                    //错误提示翻译
//                    $Helpinfo = new Helpinfo();
//                    $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
//                    //END
//                    if ($res['errcode'] == 0) {
//                        //获取存储数据
//                        $datas = $carddate->editcard($arr, 2, $info);
//                        $conten = $CardGift->save($datas, ['card_id' => $card_id]);
//                        if ($conten !== false) {
//                            $this->success('修改成功！', url('cardus/cardinfo', ['card_id' => $card_id]));
//                        } else {
//                            $this->error('修改失败', url('cardus/cardinfo', ['card_id' => $card_id]));
//                        }
//                    } else {
//                        $this->error('修改失败' . $res['errcode'] . ':' . $errmsg, url('cardus/cardinfo', ['card_id' => $card_id]), '', 30);
//                    }
                } else {
                    $Momerchant = new Momerchant();
                    $moinfo = $Momerchant->where(['id' => Session::get('login_top_mid')])->field('img_wx,merchant_name,tel,cust_call')->find();
                    $this->assign('moinfo', $moinfo);
                    $CardUrlDict = new CardUrlDict();
                    $urllist = $CardUrlDict->where('type', 1)->select();
                    $urllists = $CardUrlDict->where('type', 2)->select();
                    $Platurl = new Platurl();
                    $url['platurl'] = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
                    $this->assign('info', $info);
                    $this->assign('urllists', $urllists);
                    $this->assign('urllist', $urllist);
                    $this->assign('moinfo', $moinfo);
                    $this->assign('url', $url);
                    return $this->fetch();
                }
            } else {
                $this->success('您没有修改该会员卡权限。', 'cardus/carduslist');
            }
        }
    }

    public function cardgiftinfo(){
        $card_id = request()->param('card_id');
        $CardGift = new CardGift();
        $map['card_id'] = ['eq', $card_id];
        $map['mid'] = ['in', $this->get_mer_mid()];
        $info = $CardGift->where('card_id', $card_id)->find();
        if ($info) {
            $this->assign('info', $info);
            return $this->fetch();
        } else {
            die("<script>alert('该会员卡状态异常')</script>");
            $this->redirect('cardgift/cardgiftlist');
        }
    }

    public function getcardgiftinfo(){
        $card_id = request()->param('card_id');
//        if ($card_id && $this->checkcardid($card_id)) {
        $CardGift = new CardGift();
        $map['card_id'] = ['eq', $card_id];
        $map['mid'] = ['in', $this->get_mer_mid()];
        $info = $CardGift->where('card_id', $card_id)->find();
        if ($info){
            $info['base_info'] = json_decode($info['base_info'],true);
            $info['center'] = json_decode($info['center'],true);
            $info['custom_cell1'] = json_decode($info['custom_cell1'],true);
            $data['code'] = 0;
            $data['data'] = $info;
            $data['message'] = 'success';
        }else{
            $data['code'] = 9001;
            $data['data'] = $info;
            $data['message'] = 'error';
        }
        return json($data);
    }

    //删除卡券
    public function delcardgift()
    {
        $param =  request()->post();
        if (Request()->isAjax()) {
            $card_id = request()->post('card_id');
//        if ($card_id && $this->checkcardid($card_id)) {
            $CardGift = new CardGift();
            $data['card_id'] = $card_id;
            //初始化微信API
            $options = $this->options($card_id);
            $wxObj = new Wxobjopen($options);
            $res = $wxObj->delUserCard($data);
            if ($res['errcode'] == 0) {
                $CardGift->where('card_id', $card_id)->delete();
                $CardUserGetGift = new CardUserGetGift();
                $CardUserGetGift->where(['card_id' => $card_id])->delete();
                $rarr['code'] = 0;
                $rarr['message'] = '删除成功';
                $rarr['url'] = 'cardgifts/cardgiftlist';
            } else {
                //错误提示翻译
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
                $rarr['code'] = 9001;
                $rarr['message'] = '删除失败-' . $res['errcode'].$errmsg;
                $rarr['url'] = 'cardgifts/cardgiftlist';
            }
            return json($rarr);
//        }else{
//            $this->success('您没有修改该会员卡操作权限。', 'cardus/carduslist');
//        }
        }
    }



    //获取二维码
    public function getqrcode(){
        $card_id = 'pCVCLv_Ek_klDC7m3UP6JgZ1FOB0';
        $data = [
            "action_name" => "QR_CARD",
            "action_info" => [
                "card" => [
                    "card_id" => $card_id,
                    "outer_str" => 501
                ],
            ]
        ];
        //微信
        $options = $this->option(501);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->cardQrcode($data);
        var_dump($res);
    }


    //货架管理
    public function cardgiftracklist(){
        $CardGiftRack = new CardGiftRack();
        $map['top_mid'] = Session::get('login_top_mid');
        $list = $CardGiftRack->where($map)->select();
        $this->assign('list',$list);
        return $this->fetch();
    }

    //货架设置
    public function cardgiftrackinfo(){
        return $this->fetch();
    }

    //创建货架
    public function creatcardrack(){
        //微信
        if (Request()->isPost()) {
            $CardRack = new CardRack();
            $param = request()->post();
            $data = $CardRack->addcardrack($param,2);
            $CardGiftRack = new CardGiftRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $rackid = $CardGiftRack->where($map)->value('id');
            if ($rackid) {
                $ress = $CardGiftRack->allowField(true)->save($data,$map);
            }else{
                $ress = $CardGiftRack->allowField(true)->save($data);
            }
            if ($ress){
                $rarr['code'] = 0;
                $rarr['message'] = '创建成功';
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = '创建失败';
            }
            return json($rarr);
        }else{
            return $this->fetch();
        }
    }

    //修改货架
    public function editcardrack(){
        if (Request()->isAjax()) {
            $CardRack = new CardRack();
            $param = request()->post();
            $data = $CardRack->editcardrack($param,1);
            $options = $this->optiontop(Session::get('login_top_mid'));
            $wxObj = new Wxobjopen($options);
            $res = $wxObj->createGiftPage($data);
            if ($res['errcode'] == 0) {
                $adata = $CardRack->editcardrack($param,2);
                $adata['res_info'] = json_encode($res,JSON_UNESCAPED_UNICODE);
                $adata['page_id'] = $res['page_id'];
                $CardGiftRack = new CardGiftRack();
                $ress = $CardGiftRack->allowField(true)->save($adata);
                if ($ress){
                    $rarr['code'] = 0;
                    $rarr['message'] = '修改成功';
                }else{
                    $rarr['code'] = 9001;
                    $rarr['message'] = '修改失败';
                }
            }else{
                //错误提示翻译
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                $rarr['code'] = 9001;
                $rarr['message'] = '修改失败'.$res['errcode'].$errmsg;;
            }
            return json($rarr);
        }else{
            return $this->fetch();
        }
    }


    //获取货架信息
    public function getcardrack(){
        if (Request()->isAjax()){
            $CardGiftRack = new CardGiftRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $info = $CardGiftRack->where($map)->field('page_url,setup,statu,is_put,statu,wxa_appid,sub_mch_id,page_id,support_multi,address,banner_pic_url,biz_description,page_title,service_phone,support_buy_for_self,cell_1,cell_2')->find();
            if ($info){
                $info['cell_1'] = json_decode($info['cell_1'],true);
                $info['cell_2'] = json_decode($info['cell_2'],true);
                $rarr['code'] = 0;
                $rarr['data'] = $info;
                $rarr['message'] = 'success';
            }else{
                $rarr['code'] = 9001;
                $rarr['data'] = '';
                $rarr['message'] = 'error';
            }
            return json($rarr);
        }
    }

    //设置分类
    public function cardgiftrackcate(){
        if (Request()->isAjax()) {
            $param = request()->post();
            $data['category_list'] = json_encode($param['category_list'],JSON_UNESCAPED_UNICODE);
            $CardGiftRack = new CardGiftRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $res = $CardGiftRack->allowField(true)->save($data,$map);
            if ($res){
                $rarr['code'] = 0;
                $rarr['message'] = '设置成功';
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = '设置失败';
            }
            return json($rarr);
        }else{
            return $this->fetch();
        }
    }

    //获取分类
    public function getcardrackcate(){
        if (Request()->isAjax()){
            $CardGiftRack = new CardGiftRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $info = $CardGiftRack->where($map)->value('category_list');
            if ($info){
                $rarr['code'] = 0;
                $rarr['data'] = json_decode($info,true);
                $rarr['message'] = 'success';
            }else{
                $rarr['code'] = 9001;
                $rarr['data'] = '';
                $rarr['message'] = 'error';
            }
            return json($rarr);
        }
    }

    //礼品卡集合
    public function cardgiftrackthemelist(){
        return $this->fetch();
    }

    //获取礼品卡集合
    public function getgiftrackthemelist(){
        if (Request()->isAjax()){
            $param = request()->post();
            $CardGiftRack = new CardGiftRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $info = $CardGiftRack->where($map)->field('theme_list')->find();
            if ($info){
                $theme = json_decode($info['theme_list'],true);
                $data = [];
                $i = 0;
                foreach ($theme as $k=>$v){
                    $data[$k] = $v;
                    $data[$k]['id'] = $i;
                    $i = $i+1;
                }
                $rarr['code'] = 0;
                $rarr['data'] = $data;
                $rarr['message'] = 'success';
            }else{
                $rarr['code'] = 9001;
                $rarr['data'] = '';
                $rarr['message'] = 'error';
            }
            return json($rarr);
        }
    }

    //获取礼品卡集合详情
    public function getgiftracklist(){
        if (Request()->isAjax()){
            $param = request()->post();
            $CardGiftRack = new CardGiftRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $info = $CardGiftRack->where($map)->value('theme_list');
            if ($info){
                $theme = json_decode($info,true);
                $rarr['code'] = 0;
                $rarr['data'] = $theme[$param['id']];
                $rarr['message'] = 'success';
            }else{
                $rarr['code'] = 9001;
                $rarr['data'] = '';
                $rarr['message'] = 'error';
            }
            return json($rarr);
        }
    }

    //礼品卡创建
    public function cardgiftrackthemeadd(){
        if (Request()->isAjax()) {
            $param = request()->post();
            $param['pic_item_list']= $this->handlepicitemlist($param['pic_item_list']);
            $param['item_list']= $this->handleitemlistcard($param['item_list']);
            $CardGiftRack = new CardGiftRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $info = $CardGiftRack->where($map)->field('theme_list')->find();
            if ($info['theme_list'] !== '') {
                $data = json_decode($info['theme_list'], true);
                array_push($data, $param);
            }else{
                $data = [$param];
            }
            $datas['theme_list'] = json_encode($data,JSON_UNESCAPED_UNICODE);
            $res = $CardGiftRack->allowField(true)->save($datas,$map);
            if ($res){
                $rarr['code'] = 0;
                $rarr['message'] = '创建成功';
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = '创建失败';
            }
            return json($rarr);
        }else{
            return $this->fetch();
        }

    }

    //礼品卡修改
    public function cardgiftrackthemeedit(){
        if (Request()->isAjax()) {
            $CardGiftRack = new CardGiftRack();
            $param = request()->post();
            $map['top_mid'] = Session::get('login_top_mid');
            $info = $CardGiftRack->where($map)->value('theme_list');
            $info = json_decode($info,true);
            //原数据END
            $params['category_index'] = $param['category_index'];
            $params['pic_item_list']= $this->handlepicitemlist($param['pic_item_list']);
            $params['item_list']= $this->handleitemlistcard($param['item_list']);
            $params['theme_pic_url'] = $param['theme_pic_url'];
            $params['title'] = $param['title'];
            $params['title_color'] = $param['title_color'];
            //新数据END
            $info[$param['id']] = $params;
            $datas['theme_list'] = json_encode($info,JSON_UNESCAPED_UNICODE);
            //数据处理EDN
            $res = $CardGiftRack->allowField('theme_list')->save($datas,$map);
            if ($res){
                $rarr['code'] = 0;
                $rarr['message'] = '修改成功';
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = '修改失败';
            }
            return json($rarr);
        }else{
            return $this->fetch();
        }
    }

    //礼品卡集合删除
    public function cardgiftrackthemedel(){
        if (Request()->isAjax()){
            $param = request()->post();
            $CardGiftRack = new CardGiftRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $info = $CardGiftRack->where($map)->field('theme_list')->find();
            $theme = json_decode($info['theme_list'],true);
            unset($theme[$param['id']]);
            $theme = array_values($theme);
            $data['theme_list'] = json_encode($theme,JSON_UNESCAPED_UNICODE);
            $res = $CardGiftRack->save($data,$map);
            if ($res){
                $rarr['code'] = 0;
                $rarr['data'] = $data;
                $rarr['message'] = '删除成功';
            }else{
                $rarr['code'] = 9001;
                $rarr['data'] = '';
                $rarr['message'] = '删除失败';
            }
            return json($rarr);
        }
    }

    //
    public function handlepicitemlist($param){
        $data = [];
        foreach ($param['background_pic_url'] as $k=>$v){
            $data[$k]['background_pic_url'] = $v;
            $data[$k]['default_gifting_msg'] = $param['default_gifting_msg'][$k];
        }
        return $data;
    }

    public function handleitemlistcard($param){
        $data = [];
        $CardGift = new CardGift();
        foreach ($param as $k=>$v){
            $card = $CardGift->where(['card_id'=>$v['card_id']])->field('card_id,title,prerogative,pic_url')->find();
            $data[$k]['card_id'] = $v['card_id'];
            $data[$k]['title'] = $card['title'];
            $data[$k]['pic_url'] = $card['pic_url'];
            $data[$k]['desc'] = $card['prerogative'];
        }
        return $data;
    }

    //货架发布   创建/修改
    public function cardrackput(){
        $CardGiftRack = new CardGiftRack();
        $map['top_mid'] = Session::get('login_top_mid');
        $rack = $CardGiftRack->where($map)->find();
        $this->assign('rack',$rack);
        return $this->fetch();
    }

    //货架发布   创建/修改
    public function cardrackputs(){
        if (Request()->isAjax()) {
            $CardGiftRack = new CardGiftRack();
            $CardRack = new CardRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $rack = $CardGiftRack->where($map)->find();
            if (!$rack['page_id']) {
                //创建
                $data = $CardRack->cardrack($rack,1);
                $AccessToken = $this->getaccesstoken();
                $url = 'https://api.weixin.qq.com/card/giftcard/page/add?access_token=' . $AccessToken;
                $res = $this->http_post($url, json_encode($data,JSON_UNESCAPED_UNICODE));
                $res = json_decode($res, true);
                $type = 1;
            }else{
                //修改
                $data = $CardRack->cardrack($rack,2);
                $AccessToken = $this->getaccesstoken();
                $url = 'https://api.weixin.qq.com/card/giftcard/page/update?access_token=' . $AccessToken;
                $res = $this->http_post($url, json_encode($data,JSON_UNESCAPED_UNICODE));
                $res = json_decode($res, true);
                $type = 2;
            }
            if ($res['errcode'] == 0){
                if ($type == 1) {
                    $ress = urlencode($res['page_id']);
                    $datas['statu'] = 1;
                    $datas['page_id'] = $res['page_id'];
                    $datas['page_url'] = 'https://mp.weixin.qq.com/bizmall/giftcard?action=homepage&page_id='.$ress;
                    $CardGiftRack->save($datas, $map);
                }
                $rarr['code'] = 0;
                $rarr['message'] = '发布成功';
            }else{
                //错误提示翻译
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                $rarr['code'] = $res['errcode'];
                $rarr['message'] = '修改失败'.$res['errcode'].$errmsg;
            }
            return json($rarr);
        }
    }

    //货架上/下架
    public function cardrackstatu(){
        if (Request()->isAjax()) {
            $CardGiftRack = new CardGiftRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $rack = $CardGiftRack->where($map)->find();
            $data['page_id'] = $rack['page_id'];
            $data['maintain'] = false;
//            $data['all'] = 'false';
//            return json($data);
            $AccessToken = $this->getaccesstoken();
            $url = 'https://api.weixin.qq.com/card/giftcard/maintain/set?access_token='.$AccessToken;
            $res = $this->http_post($url, json_encode($data,JSON_UNESCAPED_UNICODE));
            $res = json_decode($res,true);
//            return json($res);
            if ($res['errcode'] == 0){
                $datas['statu'] = $rack['statu'] == 1?2:1;
                $CardGiftRack->save($datas,$map);
                $rarr['code'] = 0;
                $rarr['message'] = $datas['statu'] == 1?'上架':'下架'.'成功';
            }else{
                //错误提示翻译
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                $rarr['code'] = $res['errcode'];
                $rarr['message'] = '修改失败'.$res['errcode'].$errmsg;
            }
            return json($rarr);
        }
    }

    //获取accesstoken
    public function getaccesstoken(){
        $Momchant = new Momerchant();
        $wxOpen = new WxOpen();
        $map['id'] = Session::get('login_top_mid');
        $wx_open_id = $Momchant->where($map)->value('wx_open_id');
        $access = $wxOpen->where(['id'=>$wx_open_id])->value('at_access_token');
        return $access;
    }

    //商户号激活
    public function machpaygift(){
        if (Request()->isAjax()) {
            $param = request()->post();
            $data = ['sub_mch_id' =>$param['sub_mch_id']];
            $url = 'https://api.weixin.qq.com/card/giftcard/pay/whitelist/add?access_token=';
            $AccessToken = $this->getaccesstoken();
            $res = $this->http_post($url . $AccessToken, json_encode($data, JSON_UNESCAPED_UNICODE));
            $res = json_decode($res,true);
            if ($res['errcode'] == 0){
                $rarr['code'] = 0;
                $rarr['message'] = '开通成功';
                //
                $CardGiftRack = new CardGiftRack();
                $map['top_mid'] = Session::get('login_top_mid');
                $data['setup'] = 1;
                $CardGiftRack->save($data,$map);
            }else{
                //错误提示翻译
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                $rarr['code'] = $res['errcode'];
                $rarr['message'] = '修改失败'.$res['errcode'].$errmsg;
            }
            return json($rarr);
        }else{
            return $this->fetch();
        }

    }

    //绑定商户号到小程序
    public function bindingmicro(){
        if (Request()->isAjax()) {
            $param = request()->post();
            $data = ['sub_mch_id' =>$param['sub_mch_id'],'wxa_appid'=>$param['wxa_appid']];
            $url = 'https://api.weixin.qq.com/card/giftcard/pay/submch/bind?access_token=';
            $CardGiftRack = new CardGiftRack();
            $AccessToken = $this->getaccesstoken();
            $res = $this->http_post($url . $AccessToken, json_encode($data, JSON_UNESCAPED_UNICODE));
            //END
            $res = json_decode($res,true);
            if ($res['errcode'] == 0){
                $rarr['code'] = 0;
                $rarr['message'] = '绑定成功';
                //数据更新
                $map['top_mid'] = Session::get('login_top_mid');
                $data['setup'] = 2;
                $CardGiftRack->save($data,$map);
            }else{
                //错误提示翻译
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                $rarr['code'] = $res['errcode'];
                $rarr['message'] = '修改失败'.$res['errcode'].$errmsg;
            }
            return json($rarr);
        }

    }

    //上传小程序代码
    public function uploadmicrocode(){
        if (Request()->isAjax()) {
            $CardGiftRack = new CardGiftRack();
            $map['top_mid'] = Session::get('login_top_mid');
            $param = $CardGiftRack->where($map)->field('wxa_appid,page_id')->find();
            $data = ['wxa_appid' =>$param['wxa_appid'],'page_id'=>$param['page_id']];
            $url = 'https://api.weixin.qq.com/card/giftcard/wxa/set?access_token=';
            $AccessToken = $this->getaccesstoken();
            $res = $this->http_post($url . $AccessToken, json_encode($data, JSON_UNESCAPED_UNICODE));
            //END
            $res = json_decode($res,true);
            if ($res['errcode'] == 0){
                //数据更新
                $data['setup'] = 3;
                $CardGiftRack = new CardGiftRack();
                $CardGiftRack->save($data,$map);
                $rarr['code'] = 0;
                $rarr['message'] = '上传成功';
            }else{
                //错误提示翻译
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                $rarr['code'] = $res['errcode'];
                $rarr['message'] = '修改失败'.$res['errcode'].$errmsg;
            }
            return json($rarr);
        }
    }

    //核销
    public function consumegift(){
        if (Request()->isAjax()) {
            $param = request()->post();
//            return json($param);
            $CardUserGetGift = new CardUserGetGift();
            $user = $CardUserGetGift->where(['id'=>$param['id']])->find();
            $data = ['card_id' =>$user['card_id'],'code'=>$user['code']];
            $check = $this->checkgiftstatu($data);
            if ($check['code'] == 0) {
                $url = 'https://api.weixin.qq.com/card/code/consume?access_token=';
                $AccessToken = $this->getaccesstoken();
                $res = $this->http_post($url . $AccessToken, json_encode($data, JSON_UNESCAPED_UNICODE));
                //END
                $res = json_decode($res, true);
                if ($res['errcode'] == 0) {
                    $rarr['code'] = 0;
                    $rarr['message'] = '核销成功';
                    //数据更新
                    $datas['statu'] = 2;
                    $datas['consume_time'] = time();
                    $CardUserGetGift->save($datas,['id'=>$param['id']]);
                    $this->recsumegift($user,$param,$res);
                } else {
                    //错误提示翻译
                    $Helpinfo = new Helpinfo();
                    $errmsg = $Helpinfo->gethelpinfo(0, $res['code'], $res['message']);
                    $rarr['code'] = $res['errcode'];
                    $rarr['message'] = '核销失败' . $res['code'] . $errmsg;
                }
            }else{
                $rarr['code'] = $check['code'];
                $rarr['message'] = '核销失败' . $check['code'] . $check['message'];
            }
            return json($rarr);
        }
    }

    //增加核销记录
    public function recsumegift($user,$param,$res){
        $CardGiftConsume = new CardGiftConsume();

        $datac['code'] = $user['code'];
        $datac['card_id'] = $user['card_id'];
        $datac['openid'] = $user['openid'];
        $datac['top_mid'] = Session::get('login_top_mid');
        $datac['mid'] = $param['mid'];
        $datac['con_username'] = $param['nickname'];
        $datac['mode'] = 1;
        $datac['source'] = 1;
        $datac['consume_time'] = time();
        $datac['create_time'] = time();
        $datac['res_info'] = json_encode($res,JSON_UNESCAPED_UNICODE);
        $CardGiftConsume->allowField(true)->save($datac);
    }

    //核销状态查询
    public function checkgiftstatu($param){
        $data['code'] = $param['code'];
        $data['card_id'] = $param['card_id'];
        $url = 'https://api.weixin.qq.com/card/code/get?access_token=';
        $AccessToken = $this->getaccesstoken();
        $res = $this->http_post($url . $AccessToken, json_encode($data, JSON_UNESCAPED_UNICODE));
        $res = json_decode($res,true);
        if ($res['errcode'] == 0){
            if ($res['can_consume'] == true && $res['user_card_status'] == 'NORMAL'){
                $rarr['code'] = 0;
                $rarr['message'] = $res['user_card_status'];
            }else{
                $rarr['code'] = $res['errcode'];
                $rarr['message'] = $res['user_card_status'];
            }
        }else{
            $rarr['code'] = $res['errcode'];
            $rarr['message'] = $res['errmsg'];
        }
        return $rarr;
    }


    //领取列表
    public function getgiftlists(Request $request)
    {
        $CardUserGetGift = new CardUserGetGift();
        if ($request->isAjax()) {
            $param = $request->post();

            if (!empty($param['code'])) {
                $map['a.code'] = array('like', '%' . trim($param['code']) . '%');
            }
            $mchid = $this->get_mer_mid();
            $map['a.mid'] = array('in', $mchid);
            $map['a.have'] = 1;
            $map['c.nickname'] = ['neq',''];
            //END
            if ($param['type'] == "search") {
//                return json($map);
                $list = $CardUserGetGift->alias('a')
                    ->join('wn_card_gift b', 'a.card_id=b.card_id', 'left')
                    ->join('wn_card_user_get c', 'a.openid=c.openid', 'left')
                    ->where($map)
                    ->order('create_time desc')
                    ->field('a.id,a.mid,a.card_type,a.statu,a.card_id,a.openid,a.have,a.code,a.create_time,b.title as card_title,c.nickname')
                    ->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize'])->select();
                $list2 = [];
                foreach ($list as $k=>$v){
                    $list2[$k] = $v;
                    $list2[$k]['card_type'] = getcardtype($v['card_type']);
                    $list2[$k]['statu'] = $v['statu'] == 2?'已核销':'未核销';
                    $list2[$k]['have'] = $v['have'] == 1?'正常':'已删除';
                }
                unset($map['c.nickname']);
                $re_param["total"] = $CardUserGetGift->alias('a')->where($map)->count();
                //获取的记录
                $re_param["rows"] = $list2;
                return json($re_param);
            }elseif ($param['type'] == "out_excel") {
                $pub = new \app\common\controller\Pub();
                $header = ['门店', '订单号', '姓名', '卡号', '消费金额', '消费渠道', '消费时间', '操作人']; //表头,名称可自定义
                $CardGiftPayOrder = new CardGiftPayOrder();
                $list = $CardGiftPayOrder->where($map)->order('')->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize']);
                $excel = $pub->exportExcel( $header, $list, 'getgiftlists' . time() . rand(1000, 9999), "礼品卡领取数据", "getgiftlists", false);
                return "http://" . request()->server('HTTP_HOST') . "/" . $excel;
            }
        }else{
            $user = Session::get('user');
            $Merchant = new Merchant();
            $mab['top_mid'] = Session::get('login_top_mid');
            $mach = $Merchant->where($mab)->select();
            $this->assign('mach', $mach);
            $this->assign('user', $user);
            return $this->fetch();
        }
    }

    //核销列表
    public function consumecardgiftlist(Request $request){
        $CardGiftConsume = new CardGiftConsume();
        if ($request->isAjax()) {
            $param = $request->post();
            if (!empty($param['code'])) {
                $map['code'] =$param['code'];
            }
            $mchid = $this->get_mer_mid();
            $map['a.mid'] = array('in', $mchid);
            $map['a.statu'] = 0;
            //END
            if ($param['type'] == "search") {
                $list = $CardGiftConsume->alias('a')
                    ->join('wn_card_gift b', 'a.card_id=b.card_id', 'left')
                    ->where($map)
                    ->order('create_time desc')
                    ->field('a.id,a.mid,a.statu,a.source,a.card_id,a.openid,a.code,a.con_username,a.create_time,b.title as card_title')
                    ->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize'])
                    ->select();
                $list2 = [];
                foreach ($list as $k=>$v){
                    $list2[$k] = $v;
                    $list2[$k]['source'] = getcardussource($v['source']);
                }
                $re_param["total"] = $CardGiftConsume->alias('a')->where($map)->count();
                //获取的记录
                $re_param["rows"] = $list2;
                return json($re_param);
            }elseif ($param['type'] == "out_excel") {
                $pub = new \app\common\controller\Pub();
                $header = ['门店', '订单号', '姓名', '卡号', '消费金额', '消费渠道', '消费时间', '操作人']; //表头,名称可自定义
                $CardGiftPayOrder = new CardGiftPayOrder();
                $list = $CardGiftPayOrder->where($map)->order('')->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize']);
                $excel = $pub->exportExcel( $header, $list, 'consumecardgiftlist' . time() . rand(1000, 9999), "礼品卡核销数据", "consumecardgiftlist", false);
                return "http://" . request()->server('HTTP_HOST') . "/" . $excel;
            }
        }else{
            return $this->fetch();
        }

    }

    //购买记录
    public function cardgiftpaylist(Request $request){
        if ($request->isAjax()) {
            $param = $request->post();

            if (!empty($param['orderid'])) {
                $map['orderid'] = array('like', '%' . trim($param['orderid']) . '%');
            }
            $map['top_mid'] = Session::get('login_top_mid');
            //END
            if ($param['type'] == "search") {
                $CardGiftPayOrder = new CardGiftPayOrder();
                $list = $CardGiftPayOrder->where($map)->order('create_time desc')->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize'])->select();
                $re_param["total"] = $CardGiftPayOrder->where($map)->count();
                //获取的记录
                $re_param["rows"] = collection($list)->toArray();
                return json($re_param);
            }elseif ($param['type'] == "out_excel") {
                $pub = new \app\common\controller\Pub();
                $header = ['门店', '订单号', '姓名', '卡号', '消费金额', '消费渠道', '消费时间', '操作人']; //表头,名称可自定义
                $CardGiftPayOrder = new CardGiftPayOrder();
                $list = $CardGiftPayOrder->where($map)->order('')->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize']);
                $excel = $pub->exportExcel( $header, $list, 'cardgiftpaylist' . time() . rand(1000, 9999), "礼品卡购买数据", "cardgiftpaylist", false);
                return "http://" . request()->server('HTTP_HOST') . "/" . $excel;
            }
        }else{
//            echo 123;
            return $this->fetch();
        }
    }

    public function getpaycardgifts(Request $request){
        if ($request->isAjax()) {
            $param = $request->post();
            $CardGiftPayOrder = new CardGiftPayOrder();
            $map['id'] = $param['id'];
            $cardlist = $CardGiftPayOrder->where($map)->value('card_list');
            $cardlist = json_decode($cardlist,true);
            $CardGift = new CardGift();
            $data = '';
            foreach ($cardlist as $k => $v) {
                $datas[$k]['title'] = $CardGift->where(['card_id' => $v['card_id']])->value('title');
                $datas[$k]['price'] = $v['price'] / 100;
                $datas[$k]['code'] = $v['code'];
                $data .= '  礼品卡:' . $datas[$k]['title'] . '  卡号:' . $datas[$k]['code'] . '  价格:' . $datas[$k]['price'] . ';';

            }
            return json($data);
        }
    }

//    //礼品卡购买记录处理
//    function getpaycardgift($param)
//    {
//        $param = json_decode($param, true);
//        $CardGift = new \app\common\model\CardGift();
//        $data = '';
//        foreach ($param as $k => $v) {
//            $datas[$k]['title'] = $CardGift->where(['card_id' => $v['card_id']])->value('title');
//            $datas[$k]['price'] = $v['price'] / 100;
//            $datas[$k]['code'] = $v['code'];
//            $data .= '  礼品卡:' . $datas[$k]['title'] . '  卡号:' . $datas[$k]['code'] . '  价格:' . $datas[$k]['price'] . ';';
//
//        }
//        return $data;
//
//    }

    //设置库存
    public function editstocks()
    {
        $card_id = request()->param('card_id');
        if ($card_id && $this->checkcardid($card_id)) {
            if (Request()->isPost()) {
                $arr = request()->post();
                $data['card_id'] = $card_id;
                if ($arr['stock'] == 1) {
                    $data['increase_stock_value'] = $arr['stock_number'];
                } else {
                    $data['reduce_stock_value'] = $arr['stock_number'];
                }
                $options = $this->options($card_id);
                $wxObj = new Wxobjopen($options);
                $res = $wxObj->cardStock($data);
                if ($res['errcode'] == 0) {
                    $stockadd = (int)$arr['stock_number'];
                    $CardGift = new CardGift();
                    //增加
                    if ($arr['stock'] == 1) {
                        $CardGift->where('card_id', $card_id)->setInc('stocks', $stockadd);
                        //减少
                    } else {
                        $CardGift->where('card_id', $card_id)->setDec('stocks', $stockadd);
                    }
                    $this->success('修改成功', url('cardus/cardinfo', ['card_id' => $card_id]), 1);
                } else {
                    //错误提示翻译
                    $Helpinfo = new Helpinfo();
                    $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                    //END
                    $this->error('修改失败'.$res['errcode'].':'.$errmsg, url('cardus/cardinfo', ['card_id' => $card_id]), 1);
                }
            } else {
                $CardGift = new CardGift();
                $card = $CardGift->where('card_id', $card_id)->field('card_id,stocks')->find();
                $this->assign('card', $card);
                return $this->fetch();
            }
        }else{
            $this->success('您没有操作该会员卡操作权限。', 'cardus/carduslist');
        }
    }




    private function http_post($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
        } elseif ($post_file) {
            if ($is_curlFile) {
                foreach ($param as $key => $val) {
                    if (substr($val, 0, 1) == '@') {
                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));
                    }
                }
            }
            $strPOST = $param;

        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);

        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    //微信API参数 根据mid获取
    public function option($mid)
    {
        Session::set('openid', null);
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $Merchant = new Merchant();
        $merchantinfo = $Merchant->where('id', $mid)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //微信API参数 根据mid获取
    public function optiontop($top_mid)
    {
        Session::set('openid', null);
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $Momerchant = new Momerchant();
        $merchantinfo = $Momerchant->where('id', $top_mid)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        Session::set('openid', null);
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $map['id'] = $CardMember->where('card_id', $card_id)->value('mid');
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}
